import * as React from "react";
import {useState} from "react";
import {useNavigate,} from "react-router-dom";

import {Button, DatePicker, Form, Input, Modal, Radio, Space, Table} from 'antd';
import {promise} from "../../utils/http";
import moment from "moment-timezone";

const {RangePicker} = DatePicker;


function AuthStatus() {
    let navigate = useNavigate();
    promise('/check').then(value => {
        if (!value.data) {
            navigate("/login")
        }
    });
    return <div>


    </div>
}


const DataTable = () => {
    const [data, setData] = useState(() => {
        promise('/webQuery', {page: 1, size: 10}).then(resp => {
            const data = resp.data;
            setData(data)
        })
        return {number: 0, size: 10, content: []}
    })
    const [current, setCurrent] = useState({})
    const [fromData, setFromData] = useState({})
    const [isModalOpen, setIsModalOpen] = useState(false);
    const onFinish = (values) => {
        promise('/webQuery', {page: 1, size: 10, ...values}).then(resp => {
            const data = resp.data;
            setData(data)
            setFromData(values)
        })
    };
    const webLoad = (param) => {
        promise('/webQuery', param).then(resp => {
            const data = resp.data;
            setData(data)
        })
    }

    const [form] = Form.useForm()
    const [formSearch] = Form.useForm()
    const showModal = (data) => {
        data = data || {}
        const dateFormat = "YYYY-MM-DD"
        let temp = data
        delete temp.password
        if (data.validStart) {
            temp.dr = [moment(data.validStart, dateFormat), moment(data.validEnd, dateFormat)]
        }
        if (data.id) {
            setCurrent(data)
        }
        form.setFieldsValue(temp)
        setIsModalOpen(true);
    }

    const handleOk = () => {
        form.validateFields().then(values => {
            if (current.id) {
                values.id = current.id
            }
            promise('/update', values).then(resp => {
                const data = resp.success
                if (data) {
                    setCurrent({})
                    setIsModalOpen(false);
                    form.resetFields()
                    formSearch.submit()
                }
            })
        })
        //
    };
    const handleCancel = () => {
        setIsModalOpen(false);
    };
    const pageChange = async (page, pageSize) => {
        webLoad({page: page, size: pageSize, ...fromData})
    }
    const columns = [
        {
            title: '设备ID',
            dataIndex: 'keyId',
            key: 'keyId',
            render: (text) => <a>{text}</a>,
        },
        {
            title: '是否加密',
            dataIndex: 'encrypted',
            key: 'encrypted',
            render: (text, record, index) => <a>{text ? "是" : "否"}</a>,

        },
        {
            title: '有效期',
            dataIndex: 'address',
            key: 'address',
            render: (text, record, index) => <a>{record.validStart}-{record.validEnd}</a>,
        },
        {
            title: '备注',
            key: 'remark',
            dataIndex: 'remark',
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle">
                    <a onClick={() => showModal(record)}>编辑</a>
                    <a>删除</a>
                </Space>
            ),
        },
    ];
    return <div>
        <Form
            form={formSearch}
            onFinish={onFinish}
        >
            <Form.Item
                name="keys"
                label="keys"
                rules={[
                    {
                        required: false,
                    },
                ]}
            >
                <Input/>
            </Form.Item>

            <Form.Item>
                <Space size="middle">
                    <Button type="primary" htmlType="submit">
                        搜索
                    </Button>
                    <Button onClick={showModal}>新增</Button>
                </Space>
            </Form.Item>

        </Form>
        <Modal title="操作" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
            <Form
                form={form}
            >
                <Form.Item
                    name="keyId"
                    label="设备ID"
                    rules={[
                        {
                            required: true,
                        },
                    ]}
                >
                    <Input/>
                </Form.Item>
                <Form.Item
                    name="encrypted"
                    label="是否加密"
                    rules={[
                        {
                            required: false,
                        },
                    ]}
                >
                    <Radio.Group>
                        <Radio value={1}>是</Radio>
                        <Radio value={0}>否</Radio>
                    </Radio.Group>
                </Form.Item>
                <Form.Item
                    name="password"
                    label="密码(不需要修改时，留空)"
                    rules={[
                        {
                            required: false,
                        },
                    ]}
                >
                    <Input/>
                </Form.Item>
                <Form.Item
                    name="dr"
                    label="有效期"
                    rules={[
                        {
                            required: false,
                        },
                    ]}
                >
                    <RangePicker/>
                </Form.Item>
                <Form.Item
                    name="remark"
                    label="备注"
                    rules={[
                        {
                            required: false,
                        },
                    ]}
                >
                    <Input/>
                </Form.Item>


            </Form>
        </Modal>
        <Table columns={columns}
               pagination={{
                   current: Number(data.number + 1 || 1),
                   pageSize: Number(data.size),
                   total: Number(data.totalElements),
                   showSizeChanger: true,
                   showTotal: (total => `总共 ${total} 个项目`),
                   onChange: pageChange,
                   showQuickJumper: true,
                   pageSizeOptions: [5, 10, 20, 50, 100, 200],
                   onShowSizeChange: pageChange,
               }}
               rowKey={(record => record.id)}
               dataSource={data.content}/>
    </div>

}


export default function Main() {
    return <div>
        <AuthStatus/>
        <DataTable/>
    </div>
}